#!/usr/bin/env python3.9
# -*- encoding: utf-8 -*-
'''
@文件        :db.py
@说明        :数据库相关处理函数
@时间        :2022/11/29 09:09:19
@作者        :Mars
@版本        :1.0
'''

import os
import subprocess
from contextlib import contextmanager

from django.conf import settings
from django.db import transaction


@contextmanager
def auto_commit():
     # 显式的开启一个事务
    with transaction.atomic():
        # 创建事务保存点
        save_id = transaction.savepoint()
        try:
            yield   # yield为中断，有yield说明这是一个生成器，到这里就跳出去

            # 提交成功，显式的提交一次事务
            transaction.savepoint_commit(save_id)
        except Exception as e:
            transaction.savepoint_rollback(save_id) # 回滚事务
            #抛出异常，由统一异常处理程序处理
            raise e
        
def backup_db(username,password,db,filename,host="127.0.0.1",port="3306"):
    cmd_str = "mysqldump -u{username} -p{password} -h{host} -P{port} {db} > {file}".format(username=username,password=password,host=host,port=port,db=db,file=filename)
    try:
        return_info = subprocess.Popen(cmd_str, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        errs = return_info.stderr.readlines()
        # 判断最后一行是否有错误
        err_info = ""
        if len(errs) > 0:
            err_info = bytes.decode(errs[-1])
        if err_info.upper().find('ERROR') == -1:
            return ""
        else:
            return err_info
    except Exception as e:
        return e